import { getToken,setToken,removeToken } from "@/utils/auth"
import { getProfile,getUserByIdDetail,login } from '@/api/user'
export default {
  namespaced: true,//子模块开启命名空间
  state:{
    token:getToken()||'',//存储token
    userInfo: {}//
  },
  mutations:{
    updateToken(state,token){
      state.token=token
   setToken(token)
    },
    delToken(state){
      state.token=''
      //清空cookies中的token
      removeToken()
    },
    updateUserInfo(state, info) {
      state.userInfo = info
    },
    delUerInfo(state) {
      state.userInfo = {}
    }
  },
  actions:{ 
    async initToken(context,formData){
      const res =await login(formData)
      console.log(res,'res');
      if(res.code!=10000) return Message.error(res.message)
      Message.success(res.message)
      context.commit('updateToken',res.data);
    },
     // 定义函数发送请求.获取用户信息,存储vue
    async getUserInfo(context) {
      // context是Store的实例,context.commit()
      // console.log(context, 'cotext')
      try {
        const res = await getProfile()
        console.log(res, 'getUserProfile')
        const info = await getUserByIdDetail(res.data.userId)
        console.log(info, 'getUserByIdDetail')
        context.commit('updateUserInfo', { ...res.data, ...info.data })
      } catch (error) {
        console.log(error)
      }
    },
    logout(context) {
      context.commit('delToken')
      context.commit('delUerInfo')
    }}
}